import 'dart:async';

import 'package:flutter/material.dart';

import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:yuellyfactory/util/GlobalData.dart';
import 'package:yuellyfactory/views/purchase/PurchaseMaterial.dart';

import '../../eventbus/EventBusUtil.dart';
import '../../eventbus/EventRefreshBase.dart';
import '../../eventbus/EventRefreshMaterial.dart';
import '../../eventbus/EventRefreshType.dart';
import '../../util/BaseRequest.dart';
import 'package:animated_tree_view/animated_tree_view.dart' as treeview;
import '../../util/ViewUtil.dart';
import '../dto/PricePart.dart';

class PurchaseVC extends StatefulWidget {
  const PurchaseVC({super.key});

  @override
  State<PurchaseVC> createState() => _PurchaseVCState();
}

class _PurchaseVCState extends State<PurchaseVC> {

  treeview.TreeViewController? _controller;
  final formKey = GlobalKey<ShadFormState>();
  var currentSelect = "";
  final dialogKey = GlobalKey<ShadFormState>();
  StreamSubscription? streamSubscription;
  PricePart ?selectPricePart;

  var thirdDatas={};

  var sampleTree = treeview.TreeNode.root();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    getAllData();
    streamSubscription = eventBus.on<EventRefreshBase>().listen((event) {
      getAllData();
    });
  }

  @override
  void dispose() {
    if (streamSubscription != null) {
      streamSubscription!.cancel();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    return Container(

      child: DecoratedBox(
        decoration: BoxDecoration(
          borderRadius: theme.radius,
          border: Border.all(
            color: theme.colorScheme.border,
          ),
        ),
        child: ClipRRect(
          borderRadius: theme.radius,
          child: ShadResizablePanelGroup(
            children: [
              ShadResizablePanel(

                defaultSize: .2,
                minSize: .1,
                maxSize: .5,
                child:
                Card(
                  color: Colors.white,
                  child: treeview.TreeView.simple(
                      showRootNode: false,
                      focusToNewNode: false,
                      expansionIndicatorBuilder: (context, node) {
                        return treeview.ChevronIndicator.rightDown(
                          tree: node,
                          alignment: Alignment.centerRight,
                          color: Colors.grey[700],
                        );
                      },
                      indentation: const treeview.Indentation(

                          style: treeview.IndentStyle.roundJoint),
                      onItemTap: (item) {
                        print("Item tapped: ${item.key}");
                        currentSelect = item.key;
                        selectPricePart=item.data;
                        print("Item tapped: ${selectPricePart!.type}");
                        setState(() {}
                        );
                        if(selectPricePart!.type=='type'||selectPricePart!.type=='serial'){

                        }else{
                          if(selectPricePart!.type=='part'){
                            PricePart pricePart= thirdDatas[selectPricePart!.modelId];
                            eventBus.fire(EvetnRefreshMaterial(pricePart));
                          }else{
                            eventBus.fire(EvetnRefreshMaterial(selectPricePart!));
                          }
                        }
                      },
                      onTreeReady: (controller) {
                        _controller = controller;
                      },
                      builder: (context, node) =>
                          Container(
                            decoration: BoxDecoration(
                              color: currentSelect == node.key ? Colors.blue
                                  .withOpacity(0.1) : null,
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: ListTile(

                              title: Text("${node.data.name}",style: TextStyle(fontSize: ViewUtil.fontSize(22)),),
                            ),
                          ),
                      tree: sampleTree),
                ),
              ),
              ShadResizablePanel(

                defaultSize: .8,
                child:  Stack(

                  children: [
                    Visibility(
                        visible: selectPricePart!=null&&(selectPricePart!.type=='type'||selectPricePart!.type=='serial'),
                        child: Container()),
                    Visibility(
                        visible: selectPricePart!=null&&(selectPricePart!.type=='part'||selectPricePart!.type=='product'),
                        maintainState: true,
                        child: PurchaseMaterial()),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }











  void getAllData() {
    BaseRequest.postHttp("price/allmodels", parameters: {},
        canTip: true,
        context: context,
        onSuccess: (data) {
          bool result = BaseRequest.chekResponse(data, true);
          if (result) {
            dynamic datas = data["data"];

            List allModel = [];
            for (var i = 0; i < datas.length; i++) {
              var item = datas[i];
              var part = PricePart.fromJson(item);
              allModel.add(part);
            }
            GlobalData.priceData=allModel;
            initTreeDatas(allModel);
          }
        },
        onError: (error) {

        });
  }

  void initTreeDatas(List allModel) {
    var trees = treeview.TreeNode.root();
    for (PricePart priceModel in allModel) {
      if(currentSelect==''){
        currentSelect=priceModel.id;
        selectPricePart=priceModel;
      }else{
        if(currentSelect==priceModel.id){
          selectPricePart=priceModel;
        }
      }
      treeview.TreeNode node = treeview.TreeNode(
          key: priceModel.id, data: priceModel);
      //第二级
      for(PricePart secondPart in priceModel.priceModels){
        if(currentSelect==secondPart.id){
          selectPricePart=secondPart;
        }
        treeview.TreeNode secondNode=treeview.TreeNode(key: secondPart.id,data: secondPart);
        for(PricePart thirdPart in secondPart.priceModels) {
          thirdDatas[thirdPart.id]=thirdPart;
          if(currentSelect==thirdPart.id){
            selectPricePart=thirdPart;
          }
          treeview.TreeNode thirdNode=treeview.TreeNode(key: thirdPart.id,data: thirdPart);
          for(PricePart fourPart in thirdPart.priceParts){
            if(currentSelect==fourPart.id){
              selectPricePart=fourPart;
            }
            treeview.TreeNode fourNode=treeview.TreeNode(key: fourPart.id,data: fourPart);
            thirdNode.add(fourNode);
          }
          secondNode.add(thirdNode);
        }
        node.add(secondNode);

      }
      trees.add(node);
    }
    sampleTree = trees;
    setState(() {

    });
    if(selectPricePart!.type=='type'||selectPricePart!.type=='serial'){

    }else{

      if(selectPricePart!.type=='part'){
        PricePart pricePart= thirdDatas[selectPricePart!.modelId];
        eventBus.fire(EvetnRefreshMaterial(pricePart));
      }else{
        eventBus.fire(EvetnRefreshMaterial(selectPricePart!));
      }

    }
  }

}
